﻿using System;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace P2P_Backup
{
    public class P2PBackup
    {
        #region Singleton
        private static P2PBackup instance;
        public static P2PBackup Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = Storage.load("P2PBackup.xml");
                    if (instance == null) instance = new P2PBackup();
                    instance.Start();
                }
                return instance;
            }
        }
        #endregion
        private P2PBackup()
        {
            LocalBackupFileConnections = new List<connections.LocalFileConnection>();
            RemoteRestoreFileConnections = new List<connections.RemoteFileConnection>();
            RemoteBackupFileConnections = new List<connections.RemoteFileConnection>();
            LocalRestoreFileConnections = new List<connections.LocalFileConnection>();
            
            Peers = new List<RemotePeer>();
            if (MyArchive == null) MyArchive = archive.Archive.Instance;
        }


        public static int ApplicationPort = 7272;

        public string ArchivePath = @"d:\temp";
        public string ArchiveKey = "P2PBackupPass123";

        public long MaxArchiveSize = 148567;
        public archive.Archive MyArchive;

        [XmlIgnore] public List<RemotePeer> Peers;
        [XmlIgnore] public LocalPeer Local;

        [XmlIgnore] public List<connections.LocalFileConnection> LocalBackupFileConnections; //MyFiles
        [XmlIgnore] public List<connections.RemoteFileConnection> RemoteRestoreFileConnections;

        [XmlIgnore] public List<connections.RemoteFileConnection> RemoteBackupFileConnections;//Peer Files
        [XmlIgnore] public List<connections.LocalFileConnection> LocalRestoreFileConnections; 

        private Backup backup;       
        public void  StartBackup()
        {
            List<RemotePeer> peers = new List<RemotePeer>(this.Peers.Where(p => p.PerformBackup == true).ToList());
            this.backup = new Backup(this.MyArchive,peers);
        }

        public bool Save()
        {
            lock (this)
            {
                return Storage.save(this);
            }
        }
        public void Start()
        {
            Local = LocalPeer.Instance;
        }
        public void Stop()
        {
            foreach (RemotePeer p in Peers)
            {
                p.sendCommand("CLS");
            }            
        }
    }
}
